import json

from LoginWidget import *
from UploadWidget import UploadWidget
from PyQt6.QtNetwork import *

class ClientWidget(QWidget):

    resizeSignal = pyqtSignal(int, int)
    userName = ""
    client = QTcpSocket()

    def __init__(self):
        super().__init__()

        self.client.connectToHost('localhost', 6666)
        if self.client.waitForConnected():
            print("Connected to server.")
            self.client.readyRead.connect(self.receive_messages)
        else:
            message = QMessageBox()
            message.setText("Failed to connect to server.")
            message.setWindowTitle("WRONG!")
            message.exec()
            print("Failed to connect to server.")
            exit(-1)

        self.setStyleSheet("background-color: white;")

        self.loginWidget = login_Widget()
        self.uploadWidget = UploadWidget()
        self.mylayout = QVBoxLayout()

        print(self.loginWidget.getUsername())
        self.loginWidget.loginSignal.connect(self.login)
        self.loginWidget.tryLoginSignal.connect(self.tryLogin)

        self.initUI()

    def initUI(self):
        self.mylayout.addWidget(self.loginWidget)
        self.setLayout(self.mylayout)

    def tryLogin(self, username, password):
        data = [{"message": 'login'}, {"username": username, "password": password, "type": "user"}]
        json_data = json.dumps(data)
        self.client.write(json_data.encode())
        print('send')

    def login(self):
        print('login')
        self.userName = self.loginWidget.getUsername()
        print('get name')
        print(self.userName)
        self.uploadWidget.setUsername(self.userName)
        print('set name')
        self.uploadWidget.setSocket(self.client)
        print('set client')
        self.mylayout.removeWidget(self.loginWidget)
        self.loginWidget.deleteLater()
        self.mylayout.addWidget(self.uploadWidget)
        self.update()
        self.resizeSignal.emit(900, 560)
        # self.resize(900, 560)

    def receive_messages(self):
        print('ready receive')
        datas = self.client.readAll().data().decode().split("###")
        for data in datas:
            if data == '':
                continue
            json_data = json.loads(data)
            if json_data[0]["message"] == 'login':
                if json_data[1]["result"] == 'success':
                    self.login()
                else:
                    message = QMessageBox()
                    message.setText("Wrong username or wrong password")
                    message.setWindowTitle("WRONG!")
                    message.exec()

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.client = ClientWidget()
        self.setCentralWidget(self.client)

        self.client.resizeSignal.connect(self.resize_connection)

        self.setWindowTitle("自动报销")
        self.initUI()

    def initUI(self):
        # self.resize(900, 560)
        self.setStyleSheet("background-color: white")

    def resize_connection(self, x, y):
        self.resize(x, y)


if __name__ == "__main__":
    app = QApplication([])

    myWindow = MainWindow()
    myWindow.show()

    app.exec()